<?php
/**
 * @author  HID丨emotion
 * @license http://www.hiders.cn
 * @version 2018/8/27 17:44
 */

namespace hiders\taobao;

use hiders\http\Curl;
use think\Exception;

class Taobao
{
    protected static $instance = [];
    protected static $handler  = null;
    protected        $option   = [];
//user_id:95731367
    private function __construct($option)
    {
        $this->option = $this->formatOption($option);
    }

    private function formatOption($option)
    {
        $default = [
            'appid'  => '',
            'secret' => '',
        ];

        return array_merge($default, $option);
    }

    public static function instance($option)
    {
        if (!isset(self::$instance[ $option['appid'] ])) {
            self::$instance[ $option['appid'] ] = new self($option);
        }

        return self::$instance[ $option['appid'] ];
    }

    public function get($method = '', $param = [])
    {
        $commonParam = array(
            'method'      => $method,
            'app_key'     => $this->option['appid'],
            'sign_method' => 'md5',
            'sign'        => '',
            // 'session'     => '',
            // 'session_key' => $this->option['secret'],
            'timestamp'   => date('Y-m-d H:i:s'),
            'format'      => 'json',
            'v'           => '2.0',
        );

        $param = array_merge($commonParam, $param);

        $param = $this->createStrParam($param);

        $res = Curl::get('https://eco.taobao.com/router/rest?' . $param);
        $res = json_decode($res, true);

        if (isset($res['error_response'])) {
            /*
            array(1) {
              ["error_response"] => array(4) {
                ["code"] => int(22)
                ["msg"] => string(14) "Invalid method"
                ["sub_msg"] => string(62) "不合法ApiName，ApiName = taobao.wireless.share.tpwd.query1"
                ["request_id"] => string(12) "zjno78dk7l22"
              }
            }
            */
            throw new Exception($res['error_response']['sub_msg']);
        }

        return reset($res);
    }

    private function createSign($paramArr)
    {
        $sign = $this->option['secret'];
        ksort($paramArr);
        foreach ($paramArr as $key => $val) {
            if ($key != '' && $val != '') {
                $sign .= $key . $val;
            }
        }
        $sign .= $this->option['secret'];
        $sign = strtoupper(md5($sign));

        return $sign;
    }

    private function createStrParam($paramArr)
    {
        if (isset($paramArr['sign'])) {
            unset($paramArr['sign']);
        }
        $strParam = '';
        foreach ($paramArr as $key => $val) {
            if ($key != '' && $val != '') {
                $strParam .= $key . '=' . urlencode($val) . '&';
            }
        }

        return $strParam . 'sign=' . $this->createSign($paramArr);
    }
}